import React, { Component } from 'react';
import { Switch } from "antd";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import TheButton from "@/components/TheButton";
import TheQueryForm from '@/components/TheQueryForm';
import TheTableExtend from "@/components/TheTableExtend";
import { knowledgePage, knowledgeStatus } from '@/request/petCircleUtil/knowledge'
import store from "@/store/store"
import _ from 'lodash';
import TheSwitch from "@/components/TheSwitch";

import { getDateTime3 } from '@/utils/getDate'
export default class Dynamic extends Component {
  constructor(props) {
    super(props)
    this.state = {
      columns: [
        {
          title: "编号",
          dataIndex: "knowledgeId",
          key: "knowledgeId",
        },
        {
          title: "文章标题",
          dataIndex: "knowledgeTitle",
          key: "knowledgeTitle",
        },
        {
          title: "知识库类目",
          dataIndex: "classifyName",
          key: "classifyName",
        },
        {
          title: "宠物类型",
          dataIndex: "petType",
          key: "petType",
          render: (text, record) => {
            return text ? text : '/'
          }
        },
        {
          title: "转发数",
          dataIndex: "shareNum",
          key: "shareNum",
          sorter: true,
        },
        {
          title: "有用",
          dataIndex: "likeNum",
          key: "likeNum",
          sorter: true,
        },
        {
          title: "无用",
          dataIndex: "nolikeNum",
          key: "nolikeNum",
          sorter: true,
        },
        {
          title: "创建时间",
          dataIndex: "createTime",
          key: "createTime",
          sorter: true,
        },
        {
          title: "创建人",
          dataIndex: "createUserName",
          key: "createUserName",
        },
        {
          title: "是否启用",
          dataIndex: "status",
          key: "status",
          fixed: 'right',
          render: (text, record) => {
            return <TheSwitch haspermi={["petCircleUtil:knowledge:status"]} checked={text === 1} onChange={(checked) => this.statusChange(checked, record.knowledgeId)} />
          }
        },
        {
          title: "操作",
          dataIndex: "",
          key: "",
          fixed: 'right',
          render: (text, record) => {
            return <TheButton haspermi={['petCircleUtil:knowledge:edit']} onClick={() => this.edit(record.knowledgeId)}>编辑</TheButton>
          }
        },
      ],
      newColumns: [],
      dataSource: [],
      selectedRowKeys: [],
      pageData: {
        current: 1,
        size: 10
      },
      total: 1,
      reviewStatus: 'S',
      form_show: true, // 是否显示搜索
      searchOption: [
        { field: 'knowledgeTitle', label: '文章标题', placeholder: '请输入文章标题', required: false, rules: [], type: 'Input', defaultValue: '', },
        { field: 'time', label: '创建时间', placeholder: '请选择', required: false, rules: [], type: 'RangePicker' },
      ],
      queryForm: {},
      orderData: { orders: [{ column: 'createTime', asc: false }] }
    }
  }
  componentDidMount() {
    this.onColumnsFilter(this.state.columns)
    let searchParams = store.getState().searchValue
    let { pageNo, pageSize, queryForm, pathName } = searchParams
    if (searchParams && pageNo && pathName == 'knowledge') {
      this.setState({
        queryForm,
        pageData: { current: pageNo, size: pageSize }
      }, () => {
        this.queryFormRef.onSetDefault({ ...queryForm })
        this.getData()
      })
    } else {
      this.getData()
    }
  }
  // 知识库内容列表
  getData = async (values) => {
    // 开始结束时间数据处理
    if (values && !_.isEmpty(values.time)) {
      values.startDate = getDateTime3(values.time[0]) + ' 00:00:00'
      values.endDate = getDateTime3(values.time[1]) + ' 23:59:59'
      delete (values.time)
    }
    // 搜素值
    this.setState({
      queryForm: values === undefined ? this.state.queryForm : { ...values },
    }, async () => {
      const params = { ...this.state.pageData, ...this.state.queryForm, ...this.state.orderData }
      // 页面刷新时搜素缓存
      store.dispatch({
        type: 'SaveSearchValues',
        data: { pathName: 'knowledge', ...params }
      })
      // 接口请求返回表格数据
      let res = await knowledgePage({ ...params })
      if (res.data && res.code === 0) {
        this.setState({
          dataSource: res.data.records,
          pageData: { current: res.data.current, size: res.data.size },
          total: res.data.total
        })
      }
    })
  }
  // 表格升序降序
  handleTableChange = (pagination, filters, sorter) => {
    let orderData = {}
    if (sorter.order) {
      orderData = { orders: [{ column: sorter.field, asc: sorter.order === 'ascend' ? true : false }] }
    } else {
      orderData = { orders: [{ column: 'createTime', asc: false }] }
    }
    this.setState({
      orderData
    }, () => {
      this.getData()
    })
  }
  // 分页
  pageChange = (current, size) => {
    this.setState({ pageData: { current, size } }, () => { this.getData() })
  };
  // 搜索
  onFormSearch(values) {
    this.setState({ pageData: { current: 1, size: 10 } }, () => { this.getData(values) })
  }
  // 重置搜索
  onReset() {
    this.setState({ queryForm: {}, orderData: { orders: [{ column: 'createTime', asc: false }] } }, () => { this.pageChange(1, 10) })
  }
  //表格title
  onColumnsFilter(value) {
    this.setState({ newColumns: value })
  }
  //批量勾选
  onChange = (newSelectedRowKeys) => { this.setState({ selectedRowKeys: newSelectedRowKeys }) }
  // 是否批量启用/禁用开关
  enable = async (knowledgeIds, type) => {
    if (knowledgeIds.length <= 0) {
      React.$message({ type: 'warning', content: `请选择知识库！` })
    } else {
      let res = await knowledgeStatus({ knowledgeIds: knowledgeIds, status: type })
      if (res.code === 0) {
        this.getData()
        this.pageChange(1, 10)
        this.setState({ selectedRowKeys: [] })
      }
    }
  }
  // 是否单个启用/禁用开关
  statusChange = async (checked, knowledgeId) => {
    const status = checked ? 1 : 0
    const res = await knowledgeStatus({ knowledgeIds: [knowledgeId], status })
    if (res.code === 0) {
      this.getData()
    }
  }
  // 新建知识库内容
  add = () => {
    this.props.history.push(`/petCircleUtil/knowledge/add/${0}`);
  }
  // 编辑知识库内容
  edit = (id) => {
    this.props.history.push(`/petCircleUtil/knowledge/add/${id}`);
  }
  render() {
    const { dataSource, pageData, total, columns, form_show, searchOption, newColumns, selectedRowKeys } = this.state
    const rowSelection = {
      selectedRowKeys, // 表格选择的Id
      preserveSelectedRowKeys: true,
      onChange: this.onChange,
    }
    return (
      <div className='p-layout-box'>
        <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
          onGetValues={(values) => this.onFormSearch(values)}
          onReset={(values) => this.onReset(values)}
        >
        </TheQueryForm>
        <TheTableExtend
          columns={columns}
          onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
          onTableRefresh={() => this.getData()}
          onColumnsFilter={(value) => this.onColumnsFilter(value)}
        >
          <TheButton type={'primary'} haspermi={['petCircleUtil:knowledge:add']} size={'middle'} onClick={() => { this.add() }}>新建</TheButton>
          <TheButton type={'default'} haspermi={['petCircleUtil:knowledge:allEnable']} size={'middle'} onClick={() => { this.enable(selectedRowKeys, 1) }}>批量启用</TheButton>
          <TheButton type={'default'} haspermi={['petCircleUtil:knowledge:allForbidden']} size={'middle'} onClick={() => { this.enable(selectedRowKeys, 0) }}>批量禁用</TheButton>
        </TheTableExtend>
        <div className="p-layout-content-pagination">
          <TheTable
            rowSelection={rowSelection}
            columns={newColumns}
            dataSource={dataSource}
            onChange={this.handleTableChange}
            rowKey={'knowledgeId'}
          />
          <ThePagination
            pageNo={pageData.current}
            pageSize={pageData.size}
            total={total}
            pageChange={this.pageChange}
          />
        </div>
      </div>
    );
  }
}
